<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 01:16:57
 * @LastEditTime: 2023-11-02 09:45:04
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Models;

use App\Traits\AutoCodeTrait;
use App\Traits\SoftDeletesTrait;

class Company extends BaseModel
    {
    use AutoCodeTrait;
    use SoftDeletesTrait;
    public $timestamps = true;
    public $table = "basedata_company";
    protected $guarded = [];
    protected $ACSign = 'COMPANY_CODE';
    public $ACPrefix = "";
    public function category()
        {
        return $this->belongsTo(CompanyCategory::class);
        }
    public function link_mans()
        {
        return $this->hasMany(CompanyLinkMan::class);
        }
    public function billtrade()
        {
        return $this->hasMany(CompanyBilltrade::class);
        }
    public function finance()
        {
        return $this->belongsTo(Dic::class, "finance_id", "key")->where(function ($q)
            {
            $q->where("code", 'PartnerType');
            });
        }
    public function deptcust()
        {
        return $this->belongsTo(Dic::class, "deptcust_id", "key")->where(function ($q)
            {
            $q->where("code", 'yesorno');
            });
        }
    public function department()
        {
        return $this->belongsTo(Department::class);
        }

    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'table_status');
            });
        }

    public function updateBalance($amount)
        {
        $this->balance += $amount;
        $this->receivable_amount = $this->balance + $this->finance_balance;
        return $this->save();
        }

    public function updateFinanceBalance($amount, $debit_amount, $credit_amount, $debit_invoice_amount = 0, $credit_invoice_amount = 0)
        {
        $this->finance_balance += $amount;
        $this->debit_amount += $debit_amount;
        $this->credit_amount += $credit_amount;
        $this->debit_invoice_amount += $debit_invoice_amount;
        $this->credit_invoice_amount += $credit_invoice_amount;
        $this->invoice_amount        = ($this->debit_invoice_amount - $this->credit_invoice_amount) * $this->finance_id;
        $this->receivable_amount     = $this->balance + $this->finance_balance;
        return $this->save();
        }
    public function scopeGetLocation($IsMaterial = 0)
        {
        return $this->first()->getLocation($IsMaterial);
        }
    public function getLocation($IsMaterial = 0)
        {
        return MpcLocation::firstOrCreate([
            'name'           => $this->name,
            'parent_id'      => 3139,
            'is_outsourcing' => 1,
            'is_material'    => $IsMaterial,
            'outfactory_id'  => $this->id,
            'address'        => '外发' . ($IsMaterial == 1 ? '原料' : '成品')
        ])->id;
        }
    }
